package com.ksm.zyz.common.interceptor;

import org.slf4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;


/**
 * controller拦截器
 * @author litao
 *
 */
public class ControllerFilter implements Filter {

    private Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Map<String,String[]> parameters = request.getParameterMap();
        logger.info("--------------------------------Http start--------------------------------");
        Enumeration enum1 = request.getHeaderNames();
        while (enum1.hasMoreElements()){
            String key = (String)enum1.nextElement();
            String value = request.getHeader(key);
            logger.info("Head-->{}:{}",key,value);
        }
        logger.info("{}",request.getRequestURI());
        logger.info("Status Code:{}",response.getStatus());
        if(parameters.size()!=0){
            for(Map.Entry<String, String[]> entry : parameters.entrySet()){
                String paramName = entry.getKey();
                String paramValue = "";
                String[] paramValueArr = entry.getValue();
                for (int i=0;paramValueArr!=null && i<paramValueArr.length;i++){
                    if(i==paramValueArr.length-1){
                        paramValue += paramValueArr[i];
                    }else {
                        paramValue += paramValueArr[i]+",";
                    }
                }
                logger.info("{}={}",paramName,paramValue);
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
        logger.info("--------------------------------Http end--------------------------------");
        logger.info("--------------------------------||||||||--------------------------------");
        logger.info("--------------------------------||||||||--------------------------------");

    }

    @Override
    public void destroy() {

    }
}
